package com.itguigu.TestCountDownLatch;

import java.util.concurrent.CountDownLatch;

/*
 * CountDownLatch ：闭锁，在完成某些运算是，只有其他所有线程的运算全部完成，当前运算才继续执行
 */
public class TestCountDownLatch {
    public static void main(String[] args) {
        final CountDownLatch latch = new CountDownLatch(5);//线程执行完一次 就减1，减到0之后就可以执行闭锁，执行后面的代码了
        LatchDemo ld = new LatchDemo(latch);

        long start = System.currentTimeMillis();
        for (int i =0;i<5;i++){
            new Thread(ld).start();
        }
        try {
            latch.await();//等待所有的线程执行完毕再执行下面的代码
        }catch (Exception e){

        }
        long end = System.currentTimeMillis();
        System.out.println("耗费时间="+(end-start));
    }
}

class LatchDemo implements Runnable{

    private CountDownLatch latch;

    public LatchDemo(CountDownLatch latch){
        this.latch = latch;
    }

    public void run() {
        try {
            for (int i =0;i<10;i++){
                if (i % 2 ==0){
                    System.out.println(i);
                }
            }
        }finally {
            latch.countDown();//线程执行完毕 减一
        }

    }
}
